package com.kd.juhaowan.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.MineGameApi;
import com.kd.juhaowan.http.model.GameModel;
import com.kd.juhaowan.http.model.HttpListData;
import com.kd.juhaowan.ui.adapter.BaseRecyclerViewAdapter;
import com.kd.juhaowan.ui.adapter.BaseViewHolder;
import com.kd.juhaowan.ui.holder.MineGameViewHolder;
import com.kd.juhaowan.ui.listener.OnItemDianzanListener;
import com.kd.juhaowan.utils.DeviceUtil;
import com.kd.juhaowan.utils.LogUtil;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class MineGameActivity extends BaseActivity implements OnItemDianzanListener {




    @BindView(R.id.gift_listview)
    RecyclerView recyclerView;

    private BaseRecyclerViewAdapter<MineGameViewHolder, GameModel> giftAdapter;
    @BindView(R.id.activity_title)
    TextView titleView;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initAdapter();
        titleView.setText("我的游戏");
//        setContentView(R.layout.activity_account_login);
        EasyHttp.post(this).api(new MineGameApi(1)).request(new HttpCallbackProxy<HttpListData<GameModel>>(this){
            @Override
            public void onHttpSuccess(HttpListData<GameModel> result, boolean cache) {

                super.onHttpSuccess(result, cache);
                giftAdapter.resetAdapterData(result.getData().getList());

            }
        });
    }

    @Override
    protected void reInitDate() {
        EasyHttp.post(this).api(new MineGameApi(1)).request(new HttpCallbackProxy<HttpListData<GameModel>>(this){
            @Override
            public void onHttpSuccess(HttpListData<GameModel> result, boolean cache) {

                super.onHttpSuccess(result, cache);
                giftAdapter.resetAdapterData(result.getData().getList());

            }
        });
    }

    @OnClick(R.id.actvity_back)
    public void onBackClick(){
        finish();
    }
    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.activity_mine_gift;
    }

    @Override
    public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int position) {

    }

    @Override
    public void onItemDianzanClick(BaseViewHolder viewHolder, int position) {
        GameModel modle =giftAdapter.getItem(position);
        if(DeviceUtil.isInstallApp(getApplicationContext(),modle.getGame_package_name())){
            final Intent intent = getApplication().getPackageManager().getLaunchIntentForPackage(modle.getGame_package_name());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            startActivity(intent);
        }else{
//            downloadView.setText("下载");
            startDownload(position,modle);
        }
    }


    private void startDownload(int position,GameModel model){
        StringBuilder builder = new StringBuilder(model.getGame_package_name().trim());
//        builder.append(gameid);
        builder.append(".apk");
        File  file = new File(getExternalCacheDir(), builder.toString());
//        mSinglePath = FileDownloadUtils.getDefaultSaveRootPath()+
////                File.separator+"feifei_save"+
//                File.separator+model.getGame_package_name().trim()+".apk";;
        String mSinglePath = file.getAbsolutePath();
        BaseDownloadTask singleTask = FileDownloader.getImpl().create(model.getUrlfile())
//                .setPath(mSinglePath,false)
                .setPath(mSinglePath,false)
                .setCallbackProgressTimes(1000)
                .setMinIntervalUpdateSpeed(1000)
                //.setTag()
                .setListener(new FileDownloadSampleListener(){
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei","pending taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes);

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        model.setDesString((int)(soFarBytes*1.0/totalBytes*100)+"%");
//                        downloadView.setText("下载中（"+(int)(soFarBytes*1.0/totalBytes*100)+"%）");
                        giftAdapter.notifyItemChanged(position,model);
                        Log.d("feifei","progress taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes+",speed:"+task.getSpeed());
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                        model.setDesString("");
                        startVersionInstallTask(new File(mSinglePath));
                        Log.d("feifei","blockComplete taskId:"+task.getId()+",filePath:"+task.getPath()+",fileName:"+task.getFilename()+",speed:"+task.getSpeed()+",isReuse:"+task.reuse());
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        model.setDesString("");
                        Log.d("feifei","completed taskId:"+task.getId()+",isReuse:"+task.reuse());
                        startVersionInstallTask(new File(mSinglePath));
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei","paused taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes);
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.d("feifei","error taskId:"+task.getId()+",e:"+e.getLocalizedMessage());
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        Log.d("feifei","warn taskId:"+task.getId());
                    }
                });
          singleTask.start();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileDownloader.getImpl().pauseAll();
    }

    public void startVersionInstallTask(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        final Uri apkUri;

        if (file == null && !file.exists()) {
            LogUtil.debugLog("gamedetal", "startVersionInstallTask ========> file is not exists");
            return;
        }

        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String authority = getApplication().getPackageName() + ".PhotoPicker";
            apkUri = FileProvider.getUriForFile(getApplicationContext(), authority, file);
//            apkUri = Uri.fromFile(file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            apkUri = Uri.fromFile(file);
        }

        LogUtil.debugLog("gamedetal", "startVersionInstallTask ========> apkUri: " + apkUri.toString());

        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        startActivity(intent);
    }


    private void initAdapter(){
        giftAdapter = new BaseRecyclerViewAdapter<MineGameViewHolder, GameModel>() {
            @NonNull
            @Override
            public MineGameViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                View view = inflater.inflate(R.layout.item_mine_game, null, false);
                MineGameViewHolder holder=new MineGameViewHolder(view);
                holder.setOnItemClickListener(getOnItemClickListener());
                return  holder;

            }

            @Override
            public void onBindViewHolder(@NonNull MineGameViewHolder holder, int position) {
                holder.setDate(getItem(position));

            }
        };
        giftAdapter.setOnItemClickListener(this);
        giftAdapter.resetAdapterData(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(giftAdapter);
    }


}
